﻿namespace KataPotter {
    public static class Basket {

        private static readonly double[] Discount =
            {
                0.0,
                0.05,
                0.10,
                0.20,
                0.25
            };

        private const double Rate = 8.0;

        public static double  CalcPrice(int[] basket) {

            int[] ribbons = CreateBasketSeries(basket);

            double sum = 0;
            for (int i = 0; i < ribbons.Length; i++) {
                sum += (ribbons[i] * (i + 1) * Rate) - (ribbons[i] * (i + 1) * Rate * Discount[i]);
            }
            return sum;
        }


        internal static int[] CreateBasketSeries( int[] basket) {
            int slotLength = CalculateSlotLength(basket);
            var series = new int[slotLength];

            do {
                int seriesSlot = GetSeries(basket) - 1;
                if (-1 == seriesSlot)
                    break;
                series[seriesSlot]++;
            } while (true);

            return series;
        }

        internal static int CalculateSlotLength(int[] basket) {
            int maxSlots = Discount.Length;
            return basket.Length > maxSlots ? maxSlots : basket.Length;
        }

        internal static int GetSeries(int[] basket) {
            int countBook = 0;
            for (var i = 0; i < basket.Length; i++) {
                if (IsNoBookInSlot(basket[i])) continue;
                basket[i]--;
                countBook++;
                if (IsMaxDicountCount(countBook))
                    break;
            }
            return countBook;
        }

        private static bool IsNoBookInSlot(int count) {
            return count <= 0;
        }

        private static bool IsMaxDicountCount(int countBook) {
            return countBook == Discount.Length;
        }
    }
}
